/*
*
* Copyright (c) 2011 Vaulting Systems International
* 
* Permission is hereby granted, free of charge, to any person obtaining a copy 
* of this software and associated documentation files (the "Software"), to deal 
* in the Software without restriction, including without limitation the rights 
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 
* of the Software, and to permit persons to whom the Software is furnished to do  
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all  
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE  
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
package com.ekeymanlib.dao;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.transform.Transformers;
import org.springframework.orm.hibernate3.HibernateCallback;

import com.ekeymanlib.domain.AppDevice;
import com.ekeymanlib.dto.Application;
import com.ekeymanlib.dto.SearchFilter;

public class AppDeviceDaoImpl extends AbstractDao implements AppDeviceDao {

	public AppDeviceDaoImpl() {}
	
	public void saveAppDevice(AppDevice appDevice){
		getHibernateTemplate().saveOrUpdate(appDevice);
	}

	@SuppressWarnings("unchecked")
	public AppDevice getAppDevice(String publicKey){
		
		AppDevice appDevice = null;
		
		String queryString = "from AppDevice where publicKey = :publicKey ";
		
		String[] paramNames = new String[1];
		paramNames[0] = "publicKey";
		
		Object[] values = new Object[1];
		values[0] = publicKey;
		
		List<AppDevice> appDevices = getHibernateTemplate().findByNamedParam(queryString, paramNames, values);
		
		if(appDevices != null && !appDevices.isEmpty()){
			appDevice = appDevices.get(0);
		}
		
		return appDevice;
	}
	
	@SuppressWarnings("unchecked")
	public AppDevice getAppDevice(String apiKey, String application, String device){
		
		AppDevice appDevice = null;
		
		String queryString = "from AppDevice a where a.application = :application " +
			" and a.device = :device and a.vendor.apiKey = :apiKey ";
		
		String[] paramNames = new String[3];
		paramNames[0] = "application";
		paramNames[1] = "device";
		paramNames[2] = "apiKey";
		
		Object[] values = new Object[3];
		values[0] = application;
		values[1] = device;
		values[2] = apiKey;
		
		List<AppDevice> appDevices = getHibernateTemplate().findByNamedParam(queryString, paramNames, values);
		
		if(appDevices != null && !appDevices.isEmpty()){
			appDevice = appDevices.get(0);
		}
		
		return appDevice;
	}
	
	public void deleteAppDevice(String publicKey){
		
		AppDevice appDevice = getAppDevice(publicKey);
		if(appDevice != null){
			getHibernateTemplate().delete(appDevice);
		}
	}
	
	public void deleteAppDeviceById(long id, String apiKey){
		
		AppDevice appDevice = getAppDeviceById(id);
		
		if(appDevice != null){
			if(apiKey.equalsIgnoreCase(appDevice.getVendor().getApiKey())){
				getHibernateTemplate().delete(appDevice);
			}
		}
	}

	public AppDevice getAppDeviceById(long id){
		return getHibernateTemplate().get(AppDevice.class, id);
	}
	
	@SuppressWarnings("unchecked")
	public List<Application> listApplications(String apiKey){
		
		final String sql = "select application from enc.appdevices a, enc.vendors v " +
			"where a.vendorId = v.id and v.apikey = '" + apiKey + "'";
		
		List<Application> applications = (List<Application>) getHibernateTemplate().execute(    
			new HibernateCallback() {      
				public Object doInHibernate(Session session) throws HibernateException {      
					SQLQuery query = session.createSQLQuery(sql);
					query.setResultTransformer(Transformers.aliasToBean(Application.class)); 
					return (List<Application>)query.list();     
					}
			}
		);  
		
		return applications; 
		
	}
	
	public long getAppDeviceCount(List<SearchFilter> searchFilters) {

		return getCount(searchFilters, AppDevice.class);
	}
	
	@SuppressWarnings("unchecked")
	public List<AppDevice> findAppDevices(List<SearchFilter> searchFilters, 
			String sortIndex, String sortOrder, int firstResult, int maxResults) {

		return findAll(searchFilters, AppDevice.class, 
				sortIndex, sortOrder, firstResult, maxResults);
	}
	
}
